package cn.thr.ymcc.service.impl;

import cn.thr.ymcc.domain.Course;
import cn.thr.ymcc.domain.CourseSummary;
import cn.thr.ymcc.domain.CourseUserLearn;
import cn.thr.ymcc.dto.PaySuccessDto;
import cn.thr.ymcc.mapper.CourseMapper;
import cn.thr.ymcc.mapper.CourseSummaryMapper;
import cn.thr.ymcc.mapper.CourseUserLearnMapper;
import cn.thr.ymcc.service.ICourseUserLearnService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author thr
 * @since 2023-02-28
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {
     @Autowired
     private CourseMapper courseMapper;

     @Autowired
     private CourseSummaryMapper courseSummaryMapper;

    /**
     * service 处理支付成功  添加用户购买课程的记录
     * @param paySuccessDto
     */
    @Transactional
    @Override
    public void paySuccess(PaySuccessDto paySuccessDto) {
        for (Long courseId : paySuccessDto.getCourseIds()) {
            //保存用户购买记录
            CourseUserLearn courseUserLearn = new CourseUserLearn();
            courseUserLearn.setCourseId(courseId);
            courseUserLearn.setLoginId(paySuccessDto.getLoginId());

            //通过courseId 去查课程 startTime endTime
            Course course = courseMapper.selectById(courseId);
            courseUserLearn.setStartTime(course.getStartTime());
            courseUserLearn.setCreateTime(course.getEndTime());
            baseMapper.insert(courseUserLearn);

            //课程销量
            CourseSummary courseSummary = courseSummaryMapper.selectById(courseId);
            courseSummary.setSaleCount(courseSummary.getSaleCount()+1);
            courseSummaryMapper.updateById(courseSummary);
        }
    }
}
